<template>
  <div class="api-platform-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">API开放平台</h2>
        <p class="page-subtitle"></p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧菜单 -->
      <div class="api-list-panel">
        <el-card class="api-list-card">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>功能菜单</span>
            </div>
          </template>
          <el-menu
            :default-active="activeMenu"
            class="api-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="usage">用量信息</el-menu-item>
            <el-menu-item index="keys">API keys</el-menu-item>
            <el-menu-item index="recharge">充值</el-menu-item>
            <el-menu-item index="bill">账单</el-menu-item>
            <el-menu-item index="/api-docs">接口文档</el-menu-item>
            <el-menu-item index="faq">常见问题</el-menu-item>
          </el-menu>
        </el-card>
      </div>

      <!-- 右侧内容区 -->
      <div class="api-detail-panel">
        <el-card class="api-detail-card">
          <template v-if="activeMenu === 'keys'">
            <div class="api-keys-header">
              <h2>API keys</h2>
              <el-button type="primary" size="large" class="create-key-btn" @click="showCreateKeyDialog = true">
                <el-icon><Plus /></el-icon>
                创建 API key
              </el-button>
            </div>
            <p class="api-keys-desc">
              列表内是你的全部 API key，API key 仅在创建时可见可复制，请妥善保存。不要与他人共享你的 API key，或将其暴露在浏览器或其他客户端代码中。<br>
              为了保护你的账户安全，我们可能会自动禁用我们发现已公开泄露的 API key。
            </p>
            <el-table :data="apiKeys" class="api-keys-table" style="width: 100%; margin-top: 20px;" v-loading="loading">
              <el-table-column prop="name" label="名称" width="180" />
              <el-table-column prop="apiKey" label="Key">
                <template #default="scope">
                  {{ maskKey(scope.row.apiKey) }}
                </template>
              </el-table-column>
              <el-table-column prop="createTime" label="创建日期" width="140">
                <template #default="scope">
                  {{ formatDate(scope.row.createTime) }}
                </template>
              </el-table-column>
              <el-table-column prop="lastUsedAt" label="最新使用日期" width="140">
                <template #default="scope">
                  {{ scope.row.lastUsedAt ? formatDate(scope.row.lastUsedAt) : '-' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="scope">
                  <el-button 
                    type="danger" 
                    size="small" 
                    class="delete-btn"
                    @click="deleteKey(scope.row)"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>

          <!-- 生成API key弹窗 -->
          <el-dialog v-model="showCreateKeyDialog" title="创建 API key" width="400px">
            <el-form :model="createKeyForm" label-width="60px">
              <el-form-item label="名称">
                <el-input v-model="createKeyForm.name" placeholder="输入 API key 的名称" />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="showCreateKeyDialog = false">取消</el-button>
                <el-button type="primary" @click="createApiKey" :disabled="!createKeyForm.name">创建</el-button>
              </span>
            </template>
          </el-dialog>

          <!-- 显示新创建的API key对话框 -->
          <el-dialog v-model="showApiKeyDialog" title="API Key 创建成功" width="500px" :close-on-click-modal="false">
            <div class="api-key-display">
              <el-alert
                title="请妥善保存您的API Key"
                type="warning"
                description="API Key仅在此处显示一次，请立即复制并妥善保存。"
                :closable="false"
                style="margin-bottom: 20px;"
              />
              <div class="api-key-info">
                <div class="key-row">
                  <span class="key-label">名称：</span>
                  <span class="key-value">{{ newApiKeyData.name }}</span>
                </div>
                <div class="key-row">
                  <span class="key-label">API Key：</span>
                  <div class="key-value-container">
                    <el-input 
                      v-model="newApiKeyData.apiKey" 
                      readonly 
                      class="api-key-input"
                    />
                    <el-button type="primary" @click="copyApiKey(newApiKeyData.apiKey)">
                      <el-icon><DocumentCopy /></el-icon>
                      复制
                    </el-button>
                  </div>
                </div>
              </div>
            </div>
            <template #footer>
              <span class="dialog-footer">
                <el-button type="primary" @click="showApiKeyDialog = false">我已保存</el-button>
              </span>
            </template>
          </el-dialog>

          <!-- 充值页面 -->
          <template v-if="activeMenu === 'recharge'">
            <div class="recharge-container">
              <h2 class="recharge-title">充值</h2>
              <div class="recharge-tabs">
                <el-button :type="rechargeTab === 'online' ? 'primary' : 'default'" @click="rechargeTab = 'online'">在线充值</el-button>
                <el-button :type="rechargeTab === 'company' ? 'primary' : 'default'" @click="rechargeTab = 'company'">对公汇款</el-button>
              </div>
              <div v-if="rechargeTab === 'online'">
                <div class="recharge-amounts">
                  <el-button v-for="amt in [10,20,50,100,300,500]" :key="amt" :type="selectedAmount === amt ? 'primary' : 'default'" @click="selectedAmount = amt">￥{{ amt }}</el-button>
                  <el-button :type="selectedAmount === 'custom' ? 'primary' : 'default'" @click="selectedAmount = 'custom'">自定义</el-button>
                  <el-link type="primary" style="margin-left: 10px;">查看价格</el-link>
                </div>
                <div class="recharge-promo">
                  <span style="color: orange;">【错峰优惠活动】北京时间每日 00:30-08:30 为错峰时段，API 调用价格大幅下调：DeepSeek-V3 降至原价的 50%，DeepSeek-R1 降至 25%，在该时段调用用户享受更经济更流畅的服务体验。<el-link type="warning">查看价格详情</el-link></span>
                </div>
                <div class="recharge-pay-title">支付方式</div>
                <div class="recharge-pay-list">
                  <div :class="['pay-item', payType === 'alipay' ? 'active' : '']" @click="payType = 'alipay'">
                    <img src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/static/img/alipay.png" alt="支付宝" class="pay-icon" />
                    <span>支付宝</span>
                  </div>
                  <div :class="['pay-item', payType === 'wechat' ? 'active' : '']" @click="payType = 'wechat'">
                    <img src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/static/img/wechatpay.png" alt="微信支付" class="pay-icon" />
                    <span>微信支付</span>
                  </div>
                </div>
                <el-button type="primary" style="width: 100%; margin-top: 20px;">去支付</el-button>
                <div class="recharge-tips">
                  <b>提示</b><br />
                  1. 充值金额仅用于调用 API 服务，网页版及 App 对话免费使用，无需充值。<br />
                  2. 充值后可以前往账单页面开具发票。
                </div>
              </div>
              <div v-else>
                <div style="margin: 40px 0; color: #888; text-align: center;">对公汇款功能开发中，敬请期待…</div>
              </div>
            </div>
          </template>

          <!-- 其他菜单内容 -->
          <div v-if="activeMenu !== 'keys' && activeMenu !== 'recharge'" style="padding: 40px; text-align: center; color: #888;">
            <span>功能开发中，敬请期待…</span>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document, Plus, Edit, Refresh, Delete, DocumentCopy } from '@element-plus/icons-vue'
import axios from 'axios'

// 菜单切换
const activeMenu = ref('keys')
const rechargeTab = ref('online')
const selectedAmount = ref(10)
const payType = ref('alipay')

const handleMenuSelect = (index) => {
  if (index === '/api-docs') {
    window.__VUE_ROUTER__ && window.__VUE_ROUTER__.push('/api-docs')
    return
  }
  activeMenu.value = index
  
  // 如果切换到API keys页面，加载数据
  if (index === 'keys') {
    loadApiKeys()
  }
}

// API key 列表
const apiKeys = ref([])
const loading = ref(false)

// key脱敏
const maskKey = (key) => {
  if (!key) return ''
  return key.slice(0, 6) + '****' + key.slice(-4)
}

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  return new Date(dateStr).toLocaleDateString('zh-CN')
}

// 获取API配置
const getApiConfig = () => {
  const token = localStorage.getItem('token')
  return {
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    }
  }
}

// 加载API Key列表
const loadApiKeys = async () => {
  try {
    loading.value = true
    const response = await axios.get('http://localhost:8080/api/keys', getApiConfig())
    if (response.data.success) {
      apiKeys.value = response.data.data
    } else {
      ElMessage.error(response.data.message || '获取API Key列表失败')
    }
  } catch (error) {
    console.error('加载API Key列表失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      ElMessage.error('加载API Key列表失败: ' + (error.response.data.message || '服务器错误'))
    } else {
      ElMessage.error('加载API Key列表失败: 网络错误')
    }
  } finally {
    loading.value = false
  }
}

// 创建API key弹窗
const showCreateKeyDialog = ref(false)
const showApiKeyDialog = ref(false)
const newApiKeyData = ref({})
const createKeyForm = reactive({ name: '' })

const createApiKey = async () => {
  if (!createKeyForm.name.trim()) {
    ElMessage.warning('请输入API Key名称')
    return
  }
  
  try {
    const response = await axios.post('http://localhost:8080/api/keys', {
      name: createKeyForm.name.trim()
    }, getApiConfig())
    
    if (response.data.success) {
      newApiKeyData.value = response.data.data
      showCreateKeyDialog.value = false
      showApiKeyDialog.value = true
      createKeyForm.name = ''
      ElMessage.success('API key 创建成功')
      // 重新加载列表
      loadApiKeys()
    } else {
      ElMessage.error(response.data.message || 'API key 创建失败')
    }
  } catch (error) {
    console.error('创建API key失败:', error)
    ElMessage.error('创建API key失败')
  }
}

// 复制API Key到剪贴板
const copyApiKey = async (apiKey) => {
  try {
    await navigator.clipboard.writeText(apiKey)
    ElMessage.success('API Key已复制到剪贴板')
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = apiKey
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
    ElMessage.success('API Key已复制到剪贴板')
  }
}

// 编辑API key名称
const editKey = (row) => {
  ElMessageBox.prompt('修改API key名称', '编辑', {
    inputValue: row.name,
    confirmButtonText: '保存',
    cancelButtonText: '取消',
  }).then(async ({ value }) => {
    if (!value.trim()) {
      ElMessage.warning('名称不能为空')
      return
    }
    
    try {
      const response = await axios.put(`/api/keys/${row.id}/name`, {
        name: value.trim()
      }, getApiConfig())
      
      if (response.data.success) {
        row.name = value.trim()
        ElMessage.success('名称已更新')
      } else {
        ElMessage.error(response.data.message || '名称更新失败')
      }
    } catch (error) {
      console.error('更新名称失败:', error)
      ElMessage.error('名称更新失败')
    }
  }).catch(() => {})
}

// 重新生成API key
const regenerateKey = (row) => {
  ElMessageBox.confirm('重新生成API key将使原有key失效，确定要继续吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await axios.post(`/api/keys/${row.id}/regenerate`, {}, getApiConfig())
      
      if (response.data.success) {
        newApiKeyData.value = response.data.data
        showApiKeyDialog.value = true
        ElMessage.success('API key 重新生成成功')
        // 重新加载列表
        loadApiKeys()
      } else {
        ElMessage.error(response.data.message || 'API key 重新生成失败')
      }
    } catch (error) {
      console.error('重新生成API key失败:', error)
      ElMessage.error('重新生成API key失败')
    }
  }).catch(() => {})
}

// 删除API key
const deleteKey = (row) => {
  ElMessageBox.confirm('确定要删除此API key吗？删除后将无法恢复。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const response = await axios.delete(`/api/keys/${row.id}`, getApiConfig())
      
      if (response.data.success) {
        ElMessage.success('API key 已删除')
        // 重新加载列表
        loadApiKeys()
      } else {
        ElMessage.error(response.data.message || 'API key 删除失败')
      }
    } catch (error) {
      console.error('删除API key失败:', error)
      ElMessage.error('删除API key失败')
    }
  }).catch(() => {})
}

// 组件挂载时加载数据
onMounted(() => {
  if (activeMenu.value === 'keys') {
    loadApiKeys()
  }
})
</script>

<style scoped>
.api-platform-container {
  min-height: 100vh;
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: #f5f7fa;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0 0 5px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 主要内容区域 */
.main-content {
  display: flex;
  gap: 20px;
  flex: 1;
  margin-bottom: 20px;
  min-height: 0;
  max-height: 100%;
  overflow-y: auto;
}

/* API列表面板 */
.api-list-panel {
  width: 250px;
  flex-shrink: 0;
}

.api-list-card {
  height: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
}

.api-menu {
  border: none;
}

.api-menu :deep(.el-menu-item) {
  height: 50px;
  line-height: 50px;
  border-radius: 8px;
  margin: 5px 0;
}

/* API详情面板 */
.api-detail-panel {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.api-detail-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  height: 100%;
  max-height: 100%;
}

.api-keys-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.api-keys-desc {
  color: #ccc;
  font-size: 15px;
  margin-bottom: 10px;
}

.api-keys-table {
  background: #fff;
  color: #222;
  border-radius: 16px;
  font-size: 16px;
}

.api-keys-table th, .api-keys-table td {
  background: #fff !important;
  color: #222 !important;
}

.api-keys-table .el-button {
  color: #222;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
    max-height: none;
  }
  
  .api-list-panel {
    width: 100%;
  }
}

@media (max-width: 768px) {
  .api-platform-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}

.recharge-container {
  background: #fff;
  color: #222;
  border-radius: 16px;
  padding: 40px 32px;
  max-width: 700px;
  margin: 0 auto;
}
.recharge-title {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 24px;
}
.recharge-tabs {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
}
.recharge-amounts {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
}
.recharge-promo {
  margin-bottom: 16px;
  font-size: 15px;
}
.recharge-pay-title {
  font-size: 18px;
  font-weight: bold;
  margin: 24px 0 12px 0;
}
.recharge-pay-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 24px;
}
.pay-item {
  display: flex;
  align-items: center;
  gap: 12px;
  background: #f5f7fa;
  border-radius: 8px;
  padding: 12px 20px;
  cursor: pointer;
  font-size: 18px;
  border: 2px solid transparent;
  transition: border 0.2s;
}
.pay-item.active {
  border: 2px solid #409eff;
  background: #e6f7ff;
}
.pay-icon {
  width: 36px;
  height: 36px;
}
.recharge-tips {
  margin-top: 32px;
  font-size: 15px;
  color: #888;
}

/* API Key相关样式 */
.create-key-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  padding: 12px 24px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
}

.create-key-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
}

.delete-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  border: none;
  border-radius: 6px;
  color: white;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(255, 107, 107, 0.3);
  transition: all 0.3s ease;
}

.delete-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.5);
}

.action-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.api-key-display {
  padding: 20px 0;
}

.api-key-info {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.key-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.key-row:last-child {
  margin-bottom: 0;
}

.key-label {
  font-weight: 600;
  color: #333;
  min-width: 80px;
}

.key-value {
  color: #666;
  font-family: 'Monaco', 'Menlo', monospace;
}

.key-value-container {
  display: flex;
  gap: 10px;
  align-items: center;
  flex: 1;
}

.api-key-input {
  flex: 1;
  font-family: 'Monaco', 'Menlo', monospace;
}

.api-key-input .el-input__inner {
  background: #fff;
  border: 1px solid #dcdfe6;
}
</style> 